﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YinLongTool .Commons
{
	public class IdWorker
	{
		private long lastTimestamp = -1L;
		private long sequenceBits = 10L;
		private long sequence = 0L;
		public long sequenceMask;
		private static long twepoch = 1361753741828L;
		private long workerIdBits = 4L;
		private long timestampLeftShift;
		private long workerId;
		private long workerIdShift;
		public long maxWorkerId;
		private static IdWorker _instance;
		public static IdWorker Instance
		{
			get
			{
				if (IdWorker._instance == null)
				{
					IdWorker._instance = new IdWorker(1L);
				}
				return IdWorker._instance;
			}
		}
		public IdWorker(long workerId)
		{
			this.workerIdShift = this.sequenceBits;
			this.maxWorkerId = (-1L ^ -1L << Convert.ToInt32(this.workerIdBits));
			this.timestampLeftShift = this.sequenceBits + (long)Convert.ToInt32(this.workerIdBits);
			this.sequenceMask = (-1L ^ -1L << Convert.ToInt32(this.sequenceBits));
			if (workerId > this.maxWorkerId || workerId < 0L)
			{
			}
			this.workerId = workerId;
		}
		public long nextId()
		{
			long num = this.timeGen();
			if (this.lastTimestamp == num)
			{
				this.sequence = (this.sequence + 1L & this.sequenceMask);
				if (this.sequence == 0L)
				{
					num = this.tilNextMillis(this.lastTimestamp);
				}
			}
			else
			{
				this.sequence = 0L;
			}
			if (num < this.lastTimestamp)
			{
			}
			this.lastTimestamp = num;
			return num - IdWorker.twepoch << Convert.ToInt32(this.timestampLeftShift) | this.workerId << Convert.ToInt32(this.workerIdShift) | this.sequence;
		}
		private long tilNextMillis(long lastTimestamp)
		{
			long num;
			for (num = this.timeGen(); num <= lastTimestamp; num = this.timeGen())
			{
			}
			return num;
		}
		private long timeGen()
		{
			return DateTime.Now.Ticks;
		}
	}
}
